//
//  UpdateAddressViewController.swift
//  d11
//
//  Created by rhonin on 2018/10/31.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON

protocol FTVCdelegte : NSObjectProtocol{
    //在协议里面，声明许多方法
    // 第一个，地址
    func change(adress:String)
    //是否成功的标志
    func ChangSucces(YON:Bool)
}

class UpdateAddressViewController: UpdateRootViewController,ZHFAddTitleAddressViewDelegate{
    var stringIDs : String?
    var controllerName = NSString()
    
    // 距离父视图顶部间距
    @IBOutlet weak var bottomViewTopConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var textFild: UITextField!
    //(二)创建一个遵守协议的对象，写在定义属性处。
    var delegate_zsj:FTVCdelegte?

    
    func cancelBtnClick(titleAddress: String, titleID: String) {
        LabProvice.text = titleAddress.count > 0 ? titleAddress : ""
        textFild.text = titleAddress.count > 0 ? titleAddress : ""
        stringIDs = titleID
    }
    

    @IBOutlet weak var LabProvice: UILabel!
    
    @IBOutlet weak var buttonSure: UIButton!
    
    @IBOutlet weak var detaileText: UITextField!

    @IBOutlet weak var viewOut: UIView!
    lazy var addTitleAddressView : ZHFAddTitleAddressView = ZHFAddTitleAddressView()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.bottomViewTopConstraint.constant = kNavigationBarHeight
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        
        let layerGradientCode = CAGradientLayer()
        layerGradientCode.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradientCode.frame = CGRect(x: 0, y: 0, width: buttonSure.frame.width, height: buttonSure.frame.height+50)
        buttonSure.layer.addSublayer(layerGradientCode)
        buttonSure.layer.cornerRadius = 5
        self.title = "修改收货地址"
        setUI()
    }
    func setUI()  {
        //这是用户的ID
        addTitleAddressView.title = "选择地址"
        addTitleAddressView.userID = 7
        addTitleAddressView.delegate = self
        addTitleAddressView.defaultHeight = 350
        UIApplication.shared.delegate?.window??.addSubview(addTitleAddressView.initAddressView())
    }
    override func viewWillDisappear(_ animated: Bool) {
        addTitleAddressView.removeFromSuperview()
    }
    
    
    @IBAction func butonSureClick(_ sender: Any) {
       
        var provinces_code = ""
        var city_code = ""
        var area_code = ""
        var streets_code = ""
        let address = self.detaileText.text
        if address?.count == 0 {
             UIHelper.alertSimpleMessage(about: "请输入详细地址", withDescription: "", in: self)
            return
        }
        let arrayID = stringIDs?.components(separatedBy: "=")
        if arrayID == nil {
            UIHelper.alertSimpleMessage(about: "请选择地址", withDescription: "", in: self)
            return
        }else{
            if arrayID!.count == 1{
                UIHelper.alertSimpleMessage(about: "请选择地址", withDescription: "", in: self)
                return
            }
        }
        for index in 0..<arrayID!.count {
            if index == 0 {
                provinces_code = arrayID?[0] ?? ""
            }else if index == 1{
                city_code = arrayID?[1] ?? ""
            }else if index == 2{
                area_code = arrayID?[2] ?? ""
            }else if index == 3{
                streets_code = arrayID?[3] ?? ""
            }
        }
       weak var this = self
        let dic = ["provinces_code":provinces_code,"city_code":city_code,"area_code":area_code,"streets_code":streets_code,"address":address]
        let progress = MBProgressHUD.showMessageNoHiden("", to: self.view)
        RequestHelper.post(atPath: "/clientsAPIs/SaveAddress", withData: dic as! Dictionary<String, String>, withCompletion: { data in
            let json = JSON(data)
            if json["succ"].boolValue{
                

                DispatchQueue.main.async {
                    progress.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "更改收货地址成功", withDescription: "", in: self)
                    
                    this?.perform(#selector(this?.popcont), with: nil, afterDelay: 0.5)

                    

                }
            }else{
                DispatchQueue.main.async {
                      progress.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "更改收货地址失败", withDescription: "", in: self)
                    
                }
            }
        },withError: {_ in 
             UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
        })
    }
    
    @IBAction func selectedAddress(_ sender: Any) {
        self.textFild.endEditing(true)
         addTitleAddressView.addAnimate()
    }
    @objc func popcont()  {
        
        delegate_zsj?.change(adress: self.LabProvice.text! + self.detaileText.text!)
        delegate_zsj?.ChangSucces(YON: true)
        
        self.navigationController?.popViewController(animated: true)
        
        //选择跳转哪一页
//        let viewCtl = self.navigationController?.viewControllers[1];
//        self.navigationController?.popToViewController(viewCtl!, animated: true)
    }
    
    
//    func Discounts()  {
//        let checkUserInfoVC = DiscountsCheckUserInfoVC(nibName:"DiscountsCheckUserInfoVC", bundle:nil)
////        self.navigationController?.popViewController(checkUserInfoVC, animated: true)
//
//        self.navigationController?.popToViewController(checkUserInfoVC, animated: true)
//
//
////        第一种 你确定 返回的 页面在哪里
////        let viewCtl = self.navigationController?.viewControllers[2];
////        self.navigationController?.popToViewController(viewCtl!, animated: true)
////        第二种 遍历 navigationController 栈  里      viewControllers
////        for VC in (self.navigationController?.viewControllers)! {
////
////            if VC.isEqual(AccountSafetyCtl.self) { // AccountSafetyCtl  是你要返回的控制器（页面）
////
////                self.navigationController?.popToViewController(VC, animated: true)
////            }
////        }
//
//
//    }
    
    func popDiscountVc(adress:String){
        
    }


}
